package com.zhp.service.impl;

import com.zhp.dao.DeptDao;
import com.zhp.model.Dept;
import com.zhp.service.DeptService;

import java.util.*;

public class DeptServiceImpl implements DeptService {

    private DeptDao deptDao  =new DeptDao();
    @Override
    public List<Dept> getAll() {
        return deptDao.findAll();
    }

    @Override
    public List<Map<String, Object>> getDeptList() {
       //查出所有数据
        List<Map<String, Object>> all = deptDao.findUserList();
        //定义一个不能重复得部门id集合
        Set<String> ids = new HashSet<>();
        // 部门列表数据，用了返回的
        List<Map<String,Object>> deptList = new ArrayList<>();
        Map<String,Object> deptMap;
        //遍历所有数据
        for (Map<String,Object> map :all) {
            String deptId = map.get("dept_id").toString();
            if (!ids.contains(deptId)){
                //不存在这个部门Id
                deptMap = new HashMap<>();
                deptMap.put("deptId",deptId);
                deptMap.put("deptName",map.get("dept_name"));
               if (null == map.get("user_id")){
                   deptMap.put("deptCount",0);
               }else {
                   deptMap.put("deptCount",1);
               }
                deptList.add(deptMap);
            }else {
                for (Map<String,Object> dept:deptList) {
                    if (deptId.equals(dept.get("deptId").toString())){
                        int count = Integer.parseInt(dept.get("deptCount").toString());
                        dept.put("depyCount",++count);
                        break;
                    }
                }
            }
            ids.add(deptId);
        }
        //然后还要给部门添加员工
        List<Map<String, Object>> userList;
        Map<String,Object> userMap;
        for (Map<String,Object> dept:deptList) {
            String dId = dept.get("deptId").toString();
            userList = new ArrayList<>();
            //遍历元数据，添加员工信息到userList
            for (Map<String,Object> map:all){
                String deptId = map.get("dept_id").toString();
                if (deptId.equals(dId)){
                    userMap = new HashMap<>();
                    userMap.put("userId",map.get("user_id"));
                    userMap.put("realName",map.get("real_name"));
                   userList.add(userMap);
                }
            }
            dept.put("userList",userList);
        }
        return deptList;
    }
}
